import { Camera, EventDispatcher, Matrix4, Object3D, Plane, Raycaster, Vector2, Vector3 } from "three";
import { windowMouseTo3DMouse } from "./Mouse";

export default class DragObject extends EventDispatcher {
    _plane = new Plane();
    _raycaster = new Raycaster();
    _pointer = new Vector2();
    _offset = new Vector3();
    _intersection = new Vector3();
    _worldPosition = new Vector3();
    _inverseMatrix = new Matrix4();
    _selected = new Object3D();
    enabled: boolean;
    recursive: boolean;
    transformGroup: boolean;
    _domElement: HTMLElement;
    _camera: Camera;
    constructor(_object: Object3D, _camera: Camera, _domElement: HTMLElement) {
        super();
        this._selected = _object;
        this.enabled = true;
        this.recursive = true;
        this.transformGroup = false;
        this._domElement = _domElement;
        this._camera = _camera
    }

    setSelelcted(selected: Object3D) {
        this._selected = selected
    }

    onPointerDown(event: Vector2) {
        if (this.enabled === false) return;
        this.updatePointer(event);
        this._raycaster.setFromCamera(this._pointer, this._camera);
        this._plane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._plane.normal), this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld));
        // if (this._raycaster.ray.intersectPlane(this._plane, this._intersection)) {
        //     // if (this._selected.parent) {
        //     //     this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert();
        //     // }
        //     this._offset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld));

        // }
        this.dispatchEvent({ type: 'dragstart', object: this._selected });
    }

    onPointerMove(event: Vector2) {
        if (this.enabled === false) return;
        this.updatePointer(event);
        this._raycaster.setFromCamera(this._pointer, this._camera);
        if (this._raycaster.ray.intersectPlane(this._plane, this._intersection)) {
            // console.log({'this._selected':this._selected })
            this._selected.position.copy(this._intersection.clone());
            // this._selected.children[0].position.set(-this._intersection.x / 2, -this._intersection.y / 2, -this._intersection.z / 2);
        }
        this.dispatchEvent({ type: 'drag', object: this._selected });
        return;
    }

    updatePointer(event: Vector2) {
        const rect = this._domElement.getBoundingClientRect();
        let _pointer = windowMouseTo3DMouse(event, {
            width: rect.width,
            height: rect.height
        })
        this._pointer.x = _pointer.x;
        this._pointer.y = _pointer.y;
    }
}